package org.jash.ting13.service

import android.content.Intent
import android.os.IBinder
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import org.jash.utils.log

class AudioService : MediaSessionService() {
    private val mediaSession:MediaSession by lazy {
        val player = ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory()).build()
        MediaSession.Builder(this, player).build()
    }
    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession = mediaSession
    override fun onTaskRemoved(rootIntent: Intent?) {
        val player = mediaSession.player
        if (!player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) {
            stopSelf()
        }
    }

    override fun onDestroy() {
        log("onDestroy")
        mediaSession.run {
            player.release()
            release()
        }
        super.onDestroy()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("onStartCommand $intent flags=$flags startId=$startId")
        return super.onStartCommand(intent, flags, startId)
    }
}